import java.io.IOException;
import java.net.Socket;

interface ChessObserver {
    void updateBoard(int[][] chessGrid, int x, int y, int player, boolean isGameOver);
}

// 定义自定义主题接口
interface ChessSubject {
    void addObserver(ChessObserver observer);
    void removeObserver(ChessObserver observer);
    void notifyObservers();
}

public class ChessController {
    private ChessBoard chessBoard;
    private NetworkManager networkManager;

    public ChessController(ChessBoard chessBoard) {
        this.chessBoard = chessBoard;
    }

    public void addObserver(ChessObserver observer) {
        chessBoard.addObserver(observer); 
    }

    public int getBoardSize() {
        return chessBoard.getSize();
    }

    public int[][] getChessGrid() {
        return chessBoard.getGrid();
    }

    public int getCurrentPlayer() {
        return chessBoard.getCurrentPlayer();
    }

    public void moveChess(int x, int y) {
        chessBoard.placeChess(x, y);
    }

    public boolean undoMove() {
        return chessBoard.undoMove();
    }

    public void resetGame() {
        chessBoard.reset();
    }

    public void saveGame(String filePath) {
        GameSaveManager.saveGame(chessBoard, filePath);
    }

    public void loadGame(String filePath) {
        GameSaveManager.loadGame(chessBoard, filePath);
    }

    public boolean checkTurn() {
        if (networkManager != null) {
            return networkManager.isMyTurn();
        }
        return true; // 如果没有网络连接，默认是自己的回合
    }

    public void enbleNetworking(boolean enabled) {
        if (enabled) {
            this.networkManager = new NetworkManager(this);
        } else {
            this.networkManager.close();
            this.networkManager = null;
        }
    }

    // 作为主机启动服务器
    public void startServer(int port) throws IOException {
        networkManager.startServer(port);
    }

    // 等待客户端连接
    public Socket waitForClient() throws IOException {
        return networkManager.waitForClient();
    }

    // 作为客户端连接服务器
    public void connectToServer(String host, int port) throws IOException {
        networkManager.connectToServer(host, port);
    }

    // 发送移动信息给对方
    public void sendMove(int x, int y) {
        if (networkManager != null) {
            try {
                networkManager.sendMove(x, y);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 关闭网络连接
    public void close() {
        networkManager.close();
    }
    
}
